package com.naton.common.utils.picture;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.engine.CropEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.utils.DateUtils;
import com.naton.common.R;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropImageEngine;

import java.io.File;
import java.util.ArrayList;

/**
 * @time: 2022/1/19
 * @author: lifuling
 * @version: v1.0
 * @file_desc:  图片裁剪引擎
 */
public class ImageCropEngine implements CropEngine {

    private Context mContext;
    //是否为裁剪为圆形
    private boolean isCircle;

    public ImageCropEngine(Context mContext , boolean isCircle) {
        this.mContext = mContext;
        this.isCircle = isCircle;
    }

    @Override
    public void onStartCrop(Fragment fragment, LocalMedia currentLocalMedia,
                            ArrayList<LocalMedia> dataSource, int requestCode) {
        String currentCropPath = currentLocalMedia.getAvailablePath();
        Uri inputUri;
        if (PictureMimeType.isContent(currentCropPath) || PictureMimeType.isHasHttp(currentCropPath)) {
            inputUri = Uri.parse(currentCropPath);
        } else {
            inputUri = Uri.fromFile(new File(currentCropPath));
        }
        String fileName = DateUtils.getCreateFileName("CROP_") + ".jpg";
        Uri destinationUri = Uri.fromFile(new File(getSandboxPath(), fileName));
        UCrop.Options options = buildOptions();
        ArrayList<String> dataCropSource = new ArrayList<>();
        for (int i = 0; i < dataSource.size(); i++) {
            LocalMedia media = dataSource.get(i);
            dataCropSource.add(media.getAvailablePath());
        }
        UCrop uCrop = UCrop.of(inputUri, destinationUri, dataCropSource);
        //options.setMultipleCropAspectRatio(buildAspectRatios(dataSource.size()));
        uCrop.withOptions(options);
        uCrop.setImageEngine(new UCropImageEngine() {
            @Override
            public void loadImage(Context context, String url, ImageView imageView) {
                if (!ImageLoaderUtils.assertValidRequest(context)) {
                    return;
                }
                Glide.with(context).load(url).into(imageView);
            }

            @Override
            public void loadImage(Context context, Uri url, int maxWidth, int maxHeight, OnCallbackListener<Bitmap> call) {
                if (!ImageLoaderUtils.assertValidRequest(context)) {
                    return;
                }
                Glide.with(context).asBitmap().override(maxWidth, maxHeight).load(url).into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        if (call != null) {
                            call.onCall(resource);
                        }
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        if (call != null) {
                            call.onCall(null);
                        }
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }
                });
            }
        });
        uCrop.start(fragment.getActivity(), fragment, requestCode);
    }

    /**
     * 配制UCrop，可根据需求自我扩展
     *
     * @return
     */
    private UCrop.Options buildOptions() {
        UCrop.Options options = new UCrop.Options();
        //是否隐藏底部控件  true 隐藏  false  不隐藏 默认显示
        options.setHideBottomControls(false);
        //是否可以手动调整裁剪范围   默认禁用
        options.setFreeStyleCropEnabled(true);
        //是否显示裁剪框
        options.setShowCropFrame(true);
        //是否显示裁剪网格
        options.setShowCropGrid(true);
        //是否为圆形头像裁剪模式
        options.setCircleDimmedLayer(isCircle);
        //设置裁剪纵横比  默认0:0   其他常用 1:1 3:4   16:9
        options.withAspectRatio(0, 0);
        //设置裁剪的输出路径
        options.setCropOutputPathDir(getSandboxPath());
        //自动裁剪和拖动居中
        options.isCropDragSmoothToCenter(false);
        //使用自定义加载器获取 uCrop 资源的位图
        options.isUseCustomLoaderBitmap(false);
        options.isForbidSkipMultipleCrop(false);
        options.setStatusBarColor(ContextCompat.getColor(mContext, R.color.ps_color_grey));
        options.setToolbarColor(ContextCompat.getColor(mContext, R.color.ps_color_grey));
        options.setToolbarWidgetColor(ContextCompat.getColor(mContext, R.color.ps_color_white));
        return options;
    }

    /**
     * 创建自定义输出目录
     *
     * @return
     */
    private String getSandboxPath() {
        File externalFilesDir = mContext.getExternalFilesDir("");
        File customFile = new File(externalFilesDir.getAbsolutePath(), "Sandbox");
        if (!customFile.exists()) {
            customFile.mkdirs();
        }
        return customFile.getAbsolutePath() + File.separator;
    }
}

